package com.itheima.easy.adapter.impl;

import com.itheima.easy.adapter.FaceToFacePayAdapter;
import com.itheima.easy.constant.TradingConstant;
import com.itheima.easy.enums.TradingEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.handler.FaceToFacePayHandler;
import com.itheima.easy.utils.EmptyUtil;
import com.itheima.easy.utils.RegisterBeanHandler;
import com.itheima.easy.vo.TradingVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 当面付适配实现
 */
@Slf4j
@Component
public class FaceToFacePayAdapterImpl implements FaceToFacePayAdapter {
    @Autowired
    RegisterBeanHandler registerBeanHandler;

    private static Map<String,String> faceToFacePayHandlers =new HashMap<>();

    static {
        faceToFacePayHandlers.put(TradingConstant.TRADING_CHANNEL_ALI_PAY,"aliFaceToFacePayHandler");
        faceToFacePayHandlers.put(TradingConstant.TRADING_CHANNEL_WECHAT_PAY,"wechatFaceToFacePayHandler");
    }

    /***
     * @description 生成交易付款码，待用户扫码付款
     * @param tradingVo 订单
     * @return  二维码路径
     */
    public TradingVo precreateTrade(TradingVo tradingVo) throws ProjectException {
        //根据渠道获得bean名称
        String faceToFacePayHandlerString = faceToFacePayHandlers.get(tradingVo.getTradingChannel());

        //从IOC容器中找到FaceToFacePayHandler实现(支付实现)
        FaceToFacePayHandler faceToFacePayHandler = registerBeanHandler
                .getBean(faceToFacePayHandlerString, FaceToFacePayHandler.class);

        //precreateTrade支付交易处理
        TradingVo tradingVoResult = faceToFacePayHandler.precreateTrade(tradingVo);
        if (EmptyUtil.isNullOrEmpty(tradingVoResult.getPlaceOrderJson())) {
            throw new ProjectException(TradingEnum.TRAD_QRCODE_FAIL);
        }
        return tradingVoResult;
    }

    /***
     * @description 扫用户出示的付款码，完成付款
     * @param tradingVo 订单
     * @return  支付结果
     */
    public TradingVo payTrade(TradingVo tradingVo) {
        //根据渠道获得bean名称
        String faceToFacePayHandlerString = faceToFacePayHandlers.get(tradingVo.getTradingChannel());

        //从IOC容器中找到FaceToFacePayHandler实现(支付实现)
        FaceToFacePayHandler faceToFacePayHandler = registerBeanHandler
                .getBean(faceToFacePayHandlerString, FaceToFacePayHandler.class);

        //payTrade支付交易处理
        TradingVo tradingVoResult = faceToFacePayHandler.payTrade(tradingVo);
        return tradingVoResult;
    }
}
